package com.study.example.gameserver.module.player.controller;

import com.sparrow.event.annotation.EventReceiver;
import com.sparrow.example_message.base.req.ReqQueryPlayerInfoPacket;
import com.sparrow.example_message.base.resp.RespQueryPlayerInfoPacket;
import com.sparrow.rpc.future.SettableRpcFuture;
import com.sparrow.rpc.util.RpcUtil;
import com.sparrow.socket.tcp.anno.PacketHandler;
import com.study.example.gameserver.module.player.service.PlayerService;
import com.study.example.gameserver.module.player.entity.Player;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@PacketHandler
@Component
public class PlayerController implements IPlayerRpcService {

    @Autowired
    PlayerService playerService;

    @EventReceiver
    public void reqQueryPlayerInfo(Player player, ReqQueryPlayerInfoPacket req) {
        RpcUtil.runAsyncRpcMethod(req.getServer() + "", IPlayerRpcService.class, service -> {
            SettableRpcFuture<RespQueryPlayerInfoPacket> future = service.getPlayerInfo(req.getPlayerId());
            future.addCallback(resp -> {
                System.out.println("rpc 返回:" + resp);
                player.sendPacket(resp);
            });
        });
    }

    @Override
    public SettableRpcFuture<RespQueryPlayerInfoPacket> getPlayerInfo(long playerId) {
        SettableRpcFuture future = new SettableRpcFuture();
        playerService.execPlayerAsync(playerId, p -> {
            RespQueryPlayerInfoPacket resp = new RespQueryPlayerInfoPacket();
            resp.setPlayerId(p.getPlayerId());
            resp.setName(p.getPlayerName());
            resp.setLevel(p.getLevel());
            resp.setServer(p.getServer());
            future.setSuccess(resp);
        });
        return future;
    }

}
